<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, TableColumnCtx } from 'element-plus'
import { Delete, Plus } from '@element-plus/icons-vue'

const formRef = ref<FormInstance>()
const dynamicValidateForm = reactive<{
	domains: DomainItem[]
	email: string
}>({
	domains: [
		{
			key: 1,
			value: '',
			email: ''
		},
	],
	email: '',
})

interface DomainItem {
	key: number
	value: string
	email: string
}
interface User {
	id: string
	name: string
	amount1: string
	amount2: string
	amount3: number
}
interface SpanMethodProps {
	row: User
	column: TableColumnCtx<User>
	rowIndex: number
	columnIndex: number
}
// 合并单元格方法
const arraySpanMethod = ({
	row,
	column,
	rowIndex,
	columnIndex,
}: SpanMethodProps) => {
	if (rowIndex % 2 === 0) {
		if (columnIndex === 0) {
			return [1, 2]
		} else if (columnIndex === 1) {
			return [0, 0]
		}
	}
}
// 新增的合并方法，用于根据name值合并单元格
const objectSpanMethodByName = ({
	row,
	column,
	rowIndex,
	columnIndex,
}: SpanMethodProps) => {
	if (columnIndex === 1) { // 只对name列进行合并
		// 计算需要合并的行数
		let rowspan = 1;
		let colspan = 1;

		// 向下查找相同name的行
		for (let i = rowIndex + 1; i < tableData.length; i++) {
			if (tableData[i].name === row.name) {
				rowspan++;
			} else {
				break;
			}
		}

		// 确定当前行是否为合并的起始行
		let isStartingRow = true;
		for (let i = 0; i < rowIndex; i++) {
			if (tableData[i].name === row.name) {
				isStartingRow = false;
				break;
			}
		}

		// 如果是起始行，则返回合并信息；否则返回0，0隐藏单元格
		if (isStartingRow) {
			return {
				rowspan: rowspan,
				colspan: colspan,
			};
		} else {
			return {
				rowspan: 0,
				colspan: 0,
			};
		}
	}
}
// 合并单元格方法
const objectSpanMethod = ({
	row,
	column,
	rowIndex,
	columnIndex,
}: SpanMethodProps) => {
	if (columnIndex === 1) {
		if (rowIndex % 2 === 0) {
			return {
				rowspan: 2,
				colspan: 1,
			}
		} else {
			return {
				rowspan: 0,
				colspan: 0,
			}
		}
	}
}
const tableData: User[] = [
	{
		id: '12987122',
		name: 'Tom',
		amount1: '234',
		amount2: '3.2',
		amount3: 10,
	},
	{
		id: '12987123',
		name: 'Tom',
		amount1: '165',
		amount2: '4.43',
		amount3: 12,
	},
	{
		id: '12987124',
		name: 'Tom',
		amount1: '324',
		amount2: '1.9',
		amount3: 9,
	},
	{
		id: '12987125',
		name: 'Tom',
		amount1: '621',
		amount2: '2.2',
		amount3: 17,
	},
	{
		id: '12987126',
		name: 'Tom',
		amount1: '539',
		amount2: '4.1',
		amount3: 15,
	},
	{
		id: '12987127',
		name: 'Jerry',
		amount1: '539',
		amount2: '4.1',
		amount3: 15,
	},
	{
		id: '12987128',
		name: 'Jerry',
		amount1: '539',
		amount2: '4.1',
		amount3: 15,
	},
]
// 移除一行
const removeDomain = (item: DomainItem) => {
	const index = dynamicValidateForm.domains.indexOf(item)
	if (index !== -1) {
		dynamicValidateForm.domains.splice(index, 1)
	}
}
// 添加一行
const addDomain = () => {
	dynamicValidateForm.domains.push({
		key: Date.now(),
		value: '',
		email: '',
	})
}
// 提交表单
const submitForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate((valid: any) => {
		if (valid) {
			console.log('submit!')
		} else {
			console.log('error submit!')
		}
	})
}
// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.resetFields()
}
</script>

<template>
	<div class="w-[800px] mx-auto mt-10">
		<el-form ref="formRef" :model="dynamicValidateForm" label-width="auto" class="demo-dynamic w-[800px] mx-auto mt-4">
			<el-form-item prop="email" label="Email" :rules="[
				{
					required: true,
					message: 'Please input email address',
					trigger: 'blur',
				},
				{
					type: 'email',
					message: 'Please input correct email address',
					trigger: ['blur', 'change'],
				},
			]">
				<el-input v-model="dynamicValidateForm.email" />
			</el-form-item>
			<el-form-item v-for="(domain, index) in dynamicValidateForm.domains" :key="domain.key" :label="'Domain' + index"
				:prop="'domains.' + index + '.value'" :rules="{
					required: true,
					message: 'domain can not be null',
					trigger: 'blur',
				}">
				<el-input v-model="domain.value" />
				<el-button @click.prevent="removeDomain(domain)" class="mt-4">
					Delete
				</el-button>
			</el-form-item>

			<el-table :data="dynamicValidateForm.domains" border stripe>
				<el-table-column label="email">
					<template #default="scope">
						<el-form-item :prop="'domains.' + scope.$index + '.email'" :rules="[
							{
								required: true,
								message: 'Please input email address',
								trigger: 'blur',
							},
							{
								type: 'email',
								message: 'Please input correct email address',
								trigger: ['blur', 'change'],
							},
						]">
							<el-input v-model="scope.row.email" />
						</el-form-item>
					</template>
				</el-table-column>
				<el-table-column label="Domain">
					<template #default="scope">
						<el-form-item :prop="'domains.' + scope.$index + '.value'" :rules="{
							required: true,
							message: 'domain can not be null',
							trigger: 'blur',
						}">
							<el-input v-model="scope.row.value" />
						</el-form-item>
					</template>
				</el-table-column>
				<el-table-column label="操作">
					<template #default="scope">
						<el-button class="mb-[18px]" :icon="Delete" @click.prevent="removeDomain(scope.row)">
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-form-item class="mt-4">
				<el-button type="primary" @click="submitForm(formRef)">保存</el-button>
				<el-button @click="addDomain" :icon="Plus">添加</el-button>
				<el-button @click="resetForm(formRef)">重置</el-button>
			</el-form-item>
		</el-form>
		<div class="w-[800px] mx-auto">
			<el-table :data="tableData" :span-method="arraySpanMethod" border style="width: 100%">
				<el-table-column prop="id" label="ID" width="180" />
				<el-table-column prop="name" label="Name" />
				<el-table-column prop="amount1" sortable label="Amount 1" />
				<el-table-column prop="amount2" sortable label="Amount 2" />
				<el-table-column prop="amount3" sortable label="Amount 3" />
			</el-table>

			<el-table :data="tableData" :span-method="objectSpanMethodByName" border style="width: 100%; margin-top: 20px">
				<el-table-column prop="id" label="ID" width="180" />
				<el-table-column prop="name" label="Name" />
				<el-table-column prop="amount1" label="Amount 1" />
				<el-table-column prop="amount2" label="Amount 2" />
				<el-table-column prop="amount3" label="Amount 3" />
			</el-table>
		</div>
	</div>
</template>